package com.xn.app.muying.activity;

import android.app.Activity;
import android.bluetooth.BluetoothAdapter;
import android.bluetooth.BluetoothDevice;
import android.content.BroadcastReceiver;
import android.content.Context;
import android.content.Intent;
import android.content.IntentFilter;
import android.graphics.drawable.Drawable;
import android.os.Bundle;
import android.os.Handler;
import android.os.Looper;
import android.os.Message;
import android.provider.Settings;
import android.util.Log;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.AdapterView;
import android.widget.BaseAdapter;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.ListView;
import android.widget.TextView;

import com.jumper.fetalheart.ADFetalHeart;
import com.jumper.fetalheart.ConnectCallback;
import com.jumper.fetalheart.Mode;
import com.jumper.fetalheart.blue.CheckDevicesCallback;
import com.jumper.fetalheart.line.HeadSetUnit;
import com.xn.app.muying.R;
import com.xn.app.muying.util.BaseActivity;
import com.xn.app.muying.util.MyAlertDialog;
import com.xn.app.muying.util.ToastUtil;

import java.lang.reflect.Method;
import java.util.ArrayList;
import java.util.List;

public class LianJieActivity extends BaseActivity {
    //有线按钮
    private Button you_xian = null;
    //蓝牙按钮
    private Button lan_ya = null;
    //蓝牙列表
    private ListView mListView = null;
    //控制搜索线程
    private static final int SCANNING = 1;
    private static final int STOP_SCAN = -1;
    /**
     * 获取蓝牙适配器
     */
    BluetoothAdapter mBluetoothAdapter = BluetoothAdapter.getDefaultAdapter();
    //
    private BlueDeviceAdapter mBlueDeviceAdapter = null;
    private BlueBroadCastRecever mBlueBroadCastRecever = null;
    //获得天使医生胎心操作类
    private ADFetalHeart mAdFetalHeart = null;
    //加载框
    MyAlertDialog dialog = null;

    private Handler handler = new Handler(Looper.getMainLooper(), new Handler.Callback() {
        @Override
        public boolean handleMessage(Message msg) {
            return false;
        }
    });
    //类对象
    public static LianJieActivity lianJieActivity = null;
    BluetoothDevice mBtDevice = null;

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_lian_jie);
        lianJieActivity = this;
        you_xian = (Button) findViewById(R.id.you_xian);
        lan_ya = (Button) findViewById(R.id.lan_ya);
        mListView = (ListView) findViewById(R.id.bl_list);
        //返回事件添加
        findViewById(R.id.guan_bi).setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                finish();
            }
        });
        //获得天使医生胎心操作类
        mAdFetalHeart = ADFetalHeart.getInstance(this);
        mBlueDeviceAdapter = new BlueDeviceAdapter(this);
        mListView.setAdapter(mBlueDeviceAdapter);
        //蓝牙设备列表
        mListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                cancelDiscovery();
                mBtDevice = (BluetoothDevice) parent.getItemAtPosition(position);
                //判断蓝牙是否配对
                if (mBtDevice.getBondState() == BluetoothDevice.BOND_NONE) {
                    ToastUtil.showToast(LianJieActivity.this,"正在配对设备...");
                    try {
                        autoBond(mBtDevice.getClass(), mBtDevice, "");//设置pin值
                        createBond(mBtDevice.getClass(), mBtDevice);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                } else {
                    try {
                        mAdFetalHeart.connect(mBtDevice);
                    } catch (Exception e) {
                        e.printStackTrace();
                    }
                }

            }
        });
        //添加单击事件
        you_xian.setOnClickListener(onClickListener);
        lan_ya.setOnClickListener(onClickListener);
        // 注册蓝牙扫描广播接收者
        mBlueBroadCastRecever = new BlueBroadCastRecever();
        IntentFilter intentFilter = new IntentFilter();
        intentFilter.addAction(BluetoothAdapter.ACTION_DISCOVERY_FINISHED);
        intentFilter.addAction(BluetoothDevice.ACTION_BOND_STATE_CHANGED);
        intentFilter.addAction(BluetoothDevice.ACTION_FOUND);
        intentFilter.addAction(BluetoothAdapter.ACTION_STATE_CHANGED);
        intentFilter.addAction(BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED);
        registerReceiver(mBlueBroadCastRecever, intentFilter);
    }

    //自动配对设置Pin值
    static public boolean autoBond(Class btClass, BluetoothDevice device, String strPin) throws Exception {
        Method autoBondMethod = btClass.getMethod("setPin", new Class[]{byte[].class});
        Boolean result = (Boolean) autoBondMethod.invoke(device, new Object[]{strPin.getBytes()});
        return result;
    }

    //开始配对
    static public boolean createBond(Class btClass, BluetoothDevice device) throws Exception {
        Method createBondMethod = btClass.getMethod("createBond");
        Boolean returnValue = (Boolean) createBondMethod.invoke(device);
        return returnValue.booleanValue();
    }

    /**
     * 单击事件
     */
    View.OnClickListener onClickListener = new View.OnClickListener() {

        @Override
        public void onClick(View v) {
            Drawable yx1 = getResources().getDrawable(R.mipmap.img_0022);
            Drawable yx2 = getResources().getDrawable(R.mipmap.img_0023);
            Drawable ly1 = getResources().getDrawable(R.mipmap.img_0024);
            Drawable ly2 = getResources().getDrawable(R.mipmap.img_0025);
            switch (v.getId()) {
                //有线连接
                case R.id.you_xian:
                    mBlueDeviceAdapter.devices = new ArrayList<>();
                    mBlueDeviceAdapter.notifyDataSetChanged();
                    you_xian.setCompoundDrawablesWithIntrinsicBounds(null, yx2, null, null);
                    lan_ya.setCompoundDrawablesWithIntrinsicBounds(null, ly1, null, null);
                    // 设置成 有线模式
                    mAdFetalHeart.setMode(Mode.LINE);
                    // 检查耳机音频线是否有插入
                    if (HeadSetUnit.checkHeadSet(LianJieActivity.this)) {
                        //连接成功
                        if (MonitorSelectActivity.mSign) {
                            //自主监测
                            startActivity(new Intent(LianJieActivity.this, RecordingActivity.class));
                        } else if (!MonitorSelectActivity.mSign) {
                            //实时监测
                            startActivity(new Intent(LianJieActivity.this, LongRecordingActivity.class));
                        }
                    } else {
                        you_xian.setCompoundDrawablesWithIntrinsicBounds(null, yx1, null, null);
                        lan_ya.setCompoundDrawablesWithIntrinsicBounds(null, ly1, null, null);
                        //无耳机插入
                        startActivity(new Intent(LianJieActivity.this, YouXianActivity.class));
                    }
                    break;
                //蓝牙连接
                case R.id.lan_ya:
                    you_xian.setCompoundDrawablesWithIntrinsicBounds(null, yx1, null, null);
                    lan_ya.setCompoundDrawablesWithIntrinsicBounds(null, ly2, null, null);
                    mBlueDeviceAdapter.clear();
                    // 设置 成 蓝牙模式
                    mAdFetalHeart.setMode(Mode.BLUE);
                    startDiscovery();
                    break;

            }
        }
    };
    ConnectCallback connectCallback = new ConnectCallback() {
        @Override
        public void onConnectSuccess() {
            //自主监测
            if (MonitorSelectActivity.mSign) {
                startActivity(new Intent(LianJieActivity.this, RecordingActivity.class));
            } else {
                //实时监测
                startActivity(new Intent(LianJieActivity.this, LongRecordingActivity.class));
            }
        }

        //  这里setting 是用来判断此设备是否需要跳到设置界面配对
        // 如果为 true就说明得先跳到设置界面
        // false 就说明设备连接失败（蓝牙的，也包括有线在使用过程中断线）
        @Override
        public void onConnectFail(boolean setting) {
            if (setting) {
                ToastUtil.showToast(LianJieActivity.this,"连接失败，请手动选择设备连接");
                Intent intent = new Intent();
                intent.setAction(Settings.ACTION_BLUETOOTH_SETTINGS);
                intent.setFlags(Intent.FLAG_ACTIVITY_NEW_TASK);
                try {
                    startActivity(intent);
                } catch (Exception ex) {
                    ex.printStackTrace();
                }
            }
        }
    };

    @Override
    protected void onResume() {
        super.onResume();
        mAdFetalHeart.setConnectCallback(connectCallback);
    }

    @Override
    protected void onPause() {
        super.onPause();
        mAdFetalHeart.setConnectCallback(null);
    }

    /**
     * 搜索蓝牙
     */
    private class BlueBroadCastRecever extends BroadcastReceiver {
        @Override
        public void onReceive(Context context, Intent intent) {
            String action = intent.getAction();
            // 搜索到蓝牙设备
            if (BluetoothDevice.ACTION_FOUND.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                mBlueDeviceAdapter.addDevices(device);
                // 扫描停止广播
            } else if (BluetoothAdapter.ACTION_DISCOVERY_FINISHED.equals(action)) {
                handler.sendEmptyMessage(STOP_SCAN);
            }//状态改变时
            else if (BluetoothDevice.ACTION_BOND_STATE_CHANGED.equals(action)) {
                BluetoothDevice device = intent.getParcelableExtra(BluetoothDevice.EXTRA_DEVICE);
                switch (device.getBondState()) {
                    case BluetoothDevice.BOND_BONDING://正在配对
                        break;
                    case BluetoothDevice.BOND_BONDED://配对结束
                        ToastUtil.showToast(LianJieActivity.this,"正在尝试连接设备...");
                        // 尝试连接蓝牙设备
                        mAdFetalHeart.connect(mBtDevice);
                        break;
                    case BluetoothDevice.BOND_NONE://取消配对/未配对
                    default:
                        break;
                }
            } else if (BluetoothAdapter.ACTION_STATE_CHANGED.equals(action)) {
                //蓝牙开关
                int state = intent.getIntExtra(BluetoothAdapter.EXTRA_STATE, BluetoothAdapter.STATE_OFF);
                switch (state) {
                    //蓝牙关闭
                    case BluetoothAdapter.STATE_OFF:
                        //蓝牙关闭
                        you_xian.setCompoundDrawablesWithIntrinsicBounds(null, getResources().getDrawable(R.mipmap.img_0022), null, null);
                        lan_ya.setCompoundDrawablesWithIntrinsicBounds(null, getResources().getDrawable(R.mipmap.img_0024), null, null);
                        mBlueDeviceAdapter.devices = new ArrayList<>();
                        mBlueDeviceAdapter.notifyDataSetChanged();
                        break;
                    //蓝牙开启
                    case BluetoothAdapter.STATE_ON:
                        break;
                }
            } else if (BluetoothAdapter.ACTION_CONNECTION_STATE_CHANGED.equals(action)) {
                //蓝牙连接状态
                int state = intent.getIntExtra(BluetoothAdapter.EXTRA_CONNECTION_STATE, BluetoothAdapter.ERROR);
                switch (state) {
                    //未连接
                    case BluetoothAdapter.STATE_DISCONNECTED:
                        break;
                    //连接中
                    case BluetoothAdapter.STATE_CONNECTING:
                        break;
                    //连接成功
                    case BluetoothAdapter.STATE_CONNECTED:
                        break;
                    //失败
                    case BluetoothAdapter.STATE_DISCONNECTING:
                        break;
                }
            }
        }
    }

    //开始搜索蓝牙设备
    private void startDiscovery() {
        if (mBluetoothAdapter == null) {
            ToastUtil.showToast(this, "本机没有找到蓝牙硬件或驱动");
        }
        // 如果本地蓝牙没有开启，则开启
        if (!mBluetoothAdapter.isEnabled()) {
            if (!BluetoothAdapter.getDefaultAdapter().isEnabled()) {
                Intent mIntent = new Intent(BluetoothAdapter.ACTION_REQUEST_ENABLE);
                startActivityForResult(mIntent, 1);
            }
        } else {
            //如果蓝牙开启
            mAdFetalHeart.checkDevices(new CheckDevicesCallback() {
                @Override
                public void onFindDevice(BluetoothDevice device) {
                    mBlueDeviceAdapter.addDevices(device);
                }
            });
            mBluetoothAdapter.startDiscovery();
            handler.sendEmptyMessage(SCANNING);
            cancelDiscoveryDelay();
        }
    }

    //蓝牙提示框

    /**
     * 接受返回的信息
     *
     * @param requestCode
     * @param resultCode
     * @param data        返回来的数据
     */
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        switch (requestCode) {
            case 1:
                //蓝牙打开成功
                if (resultCode == Activity.RESULT_OK) {
                    //开始监测
                    mAdFetalHeart.checkDevices(new CheckDevicesCallback() {
                        @Override
                        public void onFindDevice(BluetoothDevice device) {
                            mBlueDeviceAdapter.addDevices(device);
                        }
                    });
                    mBluetoothAdapter.startDiscovery();
                    handler.sendEmptyMessage(SCANNING);
                    cancelDiscoveryDelay();
                } else {
                    //蓝牙打开失败
                    you_xian.setCompoundDrawablesWithIntrinsicBounds(null, getResources().getDrawable(R.mipmap.img_0022), null, null);
                    lan_ya.setCompoundDrawablesWithIntrinsicBounds(null, getResources().getDrawable(R.mipmap.img_0024), null, null);
                }
                break;
            default:
                break;
        }
    }

    protected void cancelDiscovery() {
        mBluetoothAdapter.cancelDiscovery();
        handler.sendEmptyMessage(STOP_SCAN);
        handler.removeCallbacks(runnable);
    }

    protected void cancelDiscoveryDelay() {
        handler.postDelayed(runnable, 60000);
    }

    Runnable runnable = new Runnable() {
        @Override
        public void run() {
            cancelDiscovery();
        }
    };

    private class BlueDeviceAdapter extends BaseAdapter {
        private LayoutInflater mInflater;
        public List<BluetoothDevice> devices;

        public BlueDeviceAdapter(Context context) {
            mInflater = LayoutInflater.from(context);
            devices = new ArrayList<>();
        }

        public void addDevices(BluetoothDevice bluetoothDevice) {
            if (!devices.contains(bluetoothDevice)) {
                if(bluetoothDevice.getName()!=null&&bluetoothDevice.getName().equals("Fetal Doppler")){
                    devices.add(bluetoothDevice);
                    notifyDataSetChanged();
                }
            }
        }

        @Override
        public int getCount() {
            return devices.size();
        }

        @Override
        public Object getItem(int position) {
            return devices.get(position);
        }

        @Override
        public long getItemId(int position) {
            return position;
        }

        @Override
        public View getView(int position, View convertView, ViewGroup parent) {
            ViewHolder holder = null;
            if (convertView == null) {
                convertView = mInflater.inflate(R.layout.item_fhrdevice_layout, parent, false);
                holder = new ViewHolder();
                holder.tvBlueDeviceName = (TextView) convertView.findViewById(R.id.tvBlueDeviceName);
                holder.ivBlueConnectingState = (ImageView) convertView.findViewById(R.id.ivBlueConnecteState);
                convertView.setTag(holder);
            } else {
                holder = (ViewHolder) convertView.getTag();
            }


            if (position < devices.size())
                if (devices.get(position).getName().equals("Fetal Doppler")) {
                    holder.tvBlueDeviceName.setText("[胎心监测仪] "+devices.get(position).getName());
                } else {
                    holder.tvBlueDeviceName.setText(
                            "[" + devices.get(position).getName() + "] "
                                    + devices.get(position).getAddress()
                    );
                }

            return convertView;
        }

        private void clear() {
            devices.clear();
            notifyDataSetChanged();
        }
    }


    private static class ViewHolder {
        TextView tvBlueDeviceName;
        ImageView ivBlueConnectingState;
    }


    @Override
    protected void onDestroy() {
        super.onDestroy();
        unregisterReceiver(mBlueBroadCastRecever);
        // 做一些清理工作
        // ADFetalHeart为单例，所以只要在开始初始化的activity 里做一次清理就可
        mAdFetalHeart.onDestroy();
    }


}
